using UnityEngine;
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class ChaPingAd : MonoBehaviour
{
    private string adUnitId = "";
    public event Action OnAdCompleted;
    public event Action OnAdFailed;

    public void initIntAd()
    {
        adUnitId = (string)Data.adsConfig["type_config"]["int"];
        // 初始化回调
        MaxSdkCallbacks.Interstitial.OnAdLoadedEvent += OnInterstitialLoadedEvent;
        MaxSdkCallbacks.Interstitial.OnAdLoadFailedEvent += OnInterstitialLoadFailedEvent;
        MaxSdkCallbacks.Interstitial.OnAdDisplayedEvent += OnInterstitialDisplayedEvent;
        MaxSdkCallbacks.Interstitial.OnAdClickedEvent += OnInterstitialClickedEvent;
        MaxSdkCallbacks.Interstitial.OnAdHiddenEvent += OnInterstitialHiddenEvent;
        MaxSdkCallbacks.Interstitial.OnAdDisplayFailedEvent += OnInterstitialAdFailedToDisplayEvent;

        // 加载第一个广告
        LoadInterstitial();
    }

    private void LoadInterstitial()
    {
        Tools.Log("插屏广告", "加载中...." + adUnitId);
        MaxSdk.LoadInterstitial(adUnitId);
    }

    public void ShowInterstitialAd()
    {
        if (MaxSdk.IsInterstitialReady(adUnitId))
        {
            //SDK版本恢复
            // IOSHelper.ShowSDKIntAd();
        }
        else
        {
            //关闭蒙版
            Tools.HideAdsPanel();
        }
    }


    //暴露给oc的方法
    public void ShowIntAdNow()
    {
        if (MaxSdk.IsInterstitialReady(adUnitId))
        {
            MaxSdk.ShowInterstitial(adUnitId);
        }
    }

    public bool IsInterstitialAdReady()
    {
        return MaxSdk.IsInterstitialReady(adUnitId);
    }

    private void OnInterstitialLoadedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
        Tools.Log("插屏广告", "加载完成");
    }
    private void OnInterstitialLoadFailedEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo)
    {
        Tools.Log("插屏广告", "加载失败");
        //SDK版本恢复
        // IOSHelper.ShowSDKIntAdIM();
    }
    private void OnInterstitialDisplayedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
        Tools.Log("插屏广告", "展示成功");
    }
    private void OnInterstitialClickedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
        Tools.Log("插屏广告", "被点击");
    }
    private void OnInterstitialHiddenEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
        Tools.Log("插屏广告", "关闭");
        //关闭蒙版
        Tools.HideAdsPanel();

        LoadInterstitial();
        OnAdCompleted?.Invoke();
    }
    private void OnInterstitialAdFailedToDisplayEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo, MaxSdkBase.AdInfo adInfo)
    {
        Tools.Log("插屏广告", "展示失败");
        //关闭蒙版
        Tools.HideAdsPanel();

        LoadInterstitial();
        //SDK版本恢复
        // IOSHelper.ShowSDKIntAdIM();
        OnAdFailed?.Invoke();
    }
}